using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBDataContext.Model;
using AiyoriAoshi.MangaService;
using System.Net;
using Microsoft.Phone.Net.NetworkInformation;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using System.Windows;
using AiyoriAoshi;

class ChapterDownload
{
    private int chapterId;
    private Chapter chapter;
    //public IList<string> ImageLink;
    MangaServiceClient service = new MangaServiceClient();
    private int indexOfList = 0;
    public IList<Image> Images;
    private int countCannotDownloadData = 0;

    public ChapterDownload(int chapterId)
    {
        // TODO: Complete member initialization
        this.chapterId = chapterId;
        this.chapter = App.ViewModel.GetChapterByChapterId(this.chapterId);
    }

    public bool Start()
    {
        var ni = NetworkInterface.NetworkInterfaceType;

        if (ni == NetworkInterfaceType.None)
        {
            return false;
        }

        try
        {
            // ImageLink = App.ViewModel.GetImageLinkBaseOnChapterId(this.chapter.ChapterId);
            Images = App.ViewModel.GetImagesBaseOnChapterId(this.chapter.ChapterId);

            App.ViewModel.UpdateStatusByChapterId(this.chapter.ChapterId, 2); // Status = 2;

            if (Images.Count != 0)
            {
                //ImageDownload imageDownload = new ImageDownload(Images, this.chapter);
                //imageDownload.Start();

                string link = Images[indexOfList].Link;
                WebClient webGetImage = new WebClient();
                webGetImage.OpenReadAsync(new Uri(link, UriKind.Absolute));
                webGetImage.OpenReadCompleted += new OpenReadCompletedEventHandler(webGetImage_OpenReadCompleted);
            }
            else if (countCannotDownloadData < 3)
            {
                countCannotDownloadData++;
                service.GetDataForChapterAsync(App.KEYSITE, this.chapter.Link);
                service.GetDataForChapterCompleted += new EventHandler<GetDataForChapterCompletedEventArgs>(service_GetDataForChapterCompleted);
            }
            else
            {
                MessageBox.Show("Can't download data of chapter from server.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
        return true;
    }

    void service_GetDataForChapterCompleted(object sender, GetDataForChapterCompletedEventArgs args)
    {
        IList<string> ImageLink = args.Result;
        if (ImageLink.Count() != 0)
        {
            try
            {
                // insert link to DB
                App.ViewModel.InsertImageLinkBaseOnChapterId(this.chapter.ChapterId, ImageLink);

                string link = ImageLink[0];
                WebClient webGetImage = new WebClient();
                webGetImage.OpenReadAsync(new Uri(link, UriKind.Absolute));
                webGetImage.OpenReadCompleted += new OpenReadCompletedEventHandler(webGetImage_OpenReadCompleted);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Start();
            }
        }
        else
        {
            // SOMETHING MUST DO IF YOU CANNOT DOWNLOAD DATA
            Start();
        }
    }

    void webGetImage_OpenReadCompleted(object sender, OpenReadCompletedEventArgs args)
    {
        // string fileLink = "Shared/Download/" + manga.FolderName + "/" + manga.FolderName + ".jpg";
        IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
        string fileLink = "Shared/Download/" + ((int)iss["MangaId"]).ToString() + "/" + this.chapter.ChapterId.ToString() + "/" + indexOfList.ToString("D3") + ".jpg";
        try
        {
            if (args.Result != null)
            {
                // save image
                using (IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isofile.DirectoryExists("Shared/Download/" + ((int)iss["MangaId"]).ToString()))
                    {
                        isofile.CreateDirectory("Shared/Download/" + ((int)iss["MangaId"]).ToString());
                    }

                    if (!isofile.DirectoryExists("Shared/Download/" + ((int)iss["MangaId"]).ToString() + "/" + this.chapter.ChapterId.ToString()))
                    {
                        isofile.CreateDirectory("Shared/Download/" + ((int)iss["MangaId"]).ToString() + "/" + this.chapter.ChapterId.ToString());
                    }

                    // Create file.

                    IsolatedStorageFileStream isfs = isofile.CreateFile(fileLink);
                    //Using MemoryStream to prevent OutOfMemoryException
                    byte[] data;
                    data = new byte[args.Result.Length];
                    args.Result.Read(data, 0, data.Length);

                    isfs.Write(data, 0, data.Length);
                    isfs.Flush();
                    isfs.Close();
                }


                //// update manga's ImageName
                //App.ViewModel.UpdateMangaImageName(manga.MangaId, fileLink);
                //SetMangaImage();
                if (App.ViewModel.UpdateImageLinkBaseOnChapterIdAndIndex(this.chapter.ChapterId, indexOfList) == false)
                {
                    if (App.ViewModel.GetChapterByChapterId(this.chapterId).Status == 2)
                    {
                        indexOfList++;
                        if (indexOfList <= Images.Count - 1)
                        {
                            string link = Images[indexOfList].Link;
                            WebClient webGetImage = new WebClient();
                            webGetImage.OpenReadAsync(new Uri(link, UriKind.Absolute));
                            webGetImage.OpenReadCompleted += new OpenReadCompletedEventHandler(webGetImage_OpenReadCompleted);
                        }
                    }
                }
                // Hide loading panel
                //this.stkLoading.Visibility = Visibility.Collapsed;
            }
            else
            {
                //MessageBox.Show("Không thể tải hình ảnh của truyện");
                // Hide loading panel
                //this.stkLoading.Visibility = Visibility.Collapsed;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            Debug.WriteLine(ex.Message);
            //MessageBox.Show("Gặp lỗi khi đang tải hình ảnh của truyện: " + ex.Message);
            //// Hide loading panel
            //this.stkLoading.Visibility = Visibility.Collapsed;
        }
    }

    internal void Stop()
    {
        App.ViewModel.UpdateStatusByChapterId(this.chapterId, 0);
    }
}
